package com.hyg.module_report.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.model.GetObjectRequest;
import com.alibaba.sdk.android.oss.model.GetObjectResult;
import com.bumptech.glide.Glide;
import com.hyg.lib_base.MyView.OvalImageView;
import com.hyg.lib_base.mainUtils.BitmapUtil;
import com.hyg.lib_base.mainUtils.Utils;
import com.hyg.lib_common.ossdemo.ProgressInputStream;
import com.hyg.module_report.R;
import com.hyg.module_report.model.AdviceShowItemData;
import com.hyg.module_report.model.HealthCareData;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


/*   首页使用的养生建议适配器   */
public class HealthCareAdapter extends RecyclerView.Adapter<HealthCareAdapter.ViewHolder> {
private Context context;
private ArrayList<AdviceShowItemData> dataList;
private OnItemClickLitener mOnItemClickLitener;

public HealthCareAdapter(Context activity, ArrayList<AdviceShowItemData> dataList) {
    this.context = activity.getApplicationContext();
    this.dataList = dataList;
}

public interface OnItemClickLitener {
    void onItemClick(View view, int position);

    void onItemLongClick(View view, int position);
}

public void setOnItemClickLitener(OnItemClickLitener mOnItemClickLitener) {
    this.mOnItemClickLitener = mOnItemClickLitener;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_health_care,
            parent, false);
    ViewHolder holder = new ViewHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
    ViewHolder viewHolder = (ViewHolder) holder;
    viewHolder.bindView(dataList.get(position), position);
}

@Override
public int getItemCount() {
    if (dataList == null) {
        return 0;
    }
    return dataList.size();
}

class ViewHolder extends ImageViewHolder {
    private TextView CareTitle, CareType;
    private OvalImageView CareImage;

    public ViewHolder(View itemView) {
        super(itemView);
        CareTitle = (TextView) itemView.findViewById(R.id.CareTitle);
        CareImage = (OvalImageView) itemView.findViewById(R.id.CareImage);
    }

    public void bindView(final AdviceShowItemData HealthCareData, final int pos) {
        CareTitle.setText(HealthCareData.getName());
        CareTitle.setSelected(true);
        CareTitle.setCursorVisible(false);
        Glide.with(context)
                .load(HealthCareData.getImageUrl())
                .into(CareImage);
//            super.bindImageView(HealthCareData.getCareImageUrl(), CareImage);
        // 如果设置了回调，则设置点击事件
        if (mOnItemClickLitener != null) {
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int pos = getLayoutPosition();
                    mOnItemClickLitener.onItemClick(itemView, pos);
                    //                    Toast.makeText(context,""+pos,Toast.LENGTH_SHORT).show();
                }
            });

            itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    int pos = getLayoutPosition();
                    mOnItemClickLitener.onItemLongClick(itemView, pos);

                    return false;
                }
            });
        }


    }

}

    /* 可以用被继承的公用OSS下载图片Holder */
class ImageViewHolder extends  RecyclerView.ViewHolder {

    public ImageView imageView;
//        private static final String accessKeyId = "LTAIl8EfCBBx4cLP";
//        private static final String accessKeySecret = "TgDfIoGfSSwihX1DR1h4s5XwngSQL7";
//        private static final String endpoint = "oss-cn-beijing.aliyuncs.com";
//        private static final String bucket = "pictureupload-18-08-29";

        private static final String accessKeyId = "LTAImEYCt3oofbDP";
        private static final String accessKeySecret = "YczQrsbzVHkm7RC7PyTCBkqnycFMN4";
        private static final String endpoint = "oss-cn-beijing.aliyuncs.com";
        private static final String bucket = "health-advice";
    private int progress = 0;
    private Bitmap bm;

    ImageViewHolder(View itemView) {
        super(itemView);
    }
    public void bindImageView(final String Image_url, ImageView imageViews) {
        imageView = imageViews;
        //创建RxAndroid线程
        Observable.create(new ObservableOnSubscribe<byte[]>() {
            @Override
            public void subscribe(final ObservableEmitter<byte[]> subscriber) throws Exception {
                Log.d("oss", "subscribe");
                Bitmap bitmap = BitmapUtil.getBitmapFromSDCard(context.getExternalFilesDir(null) + Image_url);
                if (Utils.isEmpty(bitmap)) {//判断文件目录是否存在
                    initOSS(endpoint).asyncGetObject(new GetObjectRequest(bucket, Image_url),
                            new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
                                @Override
                                public void onSuccess(final GetObjectRequest request, final GetObjectResult result) {
                                    InputStream inputStream = result.getObjectContent();
                                    //重载InputStream来获取读取进度信息
                                    ProgressInputStream progressStream = new ProgressInputStream(inputStream,
                                            new OSSProgressCallback<GetObjectRequest>() {
                                                @Override
                                                public void onProgress(GetObjectRequest o, long currentSize, long totalSize) {
//                                                        Log.d("GetObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
                                                    progress = (int) (100 * currentSize / totalSize);
                                                }
                                            }, result.getContentLength());
                                    try {
                                        Log.d("oss", "progress");
                                        bm = autoResizeFromStream(progressStream);
                                        if (progress >= 100) {
                                            if (BitmapUtil.saveBitmapToSDCard(bm, context.getExternalFilesDir(null) + Image_url)) {
                                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                                bm.compress(Bitmap.CompressFormat.PNG, 80, baos);
                                                byte[] bytes = baos.toByteArray();
                                                if (bm != null) {
                                                    bm = null;
                                                }
                                                Log.d("oss", "subscriber");
                                                subscriber.onNext(bytes);
//                                                    Log.d("oss", "onNext");
                                            }
                                        }
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                                @Override
                                public void onFailure(GetObjectRequest request, ClientException clientException, ServiceException serviceException) {
                                    Throwable throwable = new Throwable("图片下载失败，请退出重试");
                                    subscriber.onError(throwable);
                                    Log.d("oss", "onFailure");
                                }
                            });
                } else {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 80, baos);
                    byte[] bytes = baos.toByteArray();
                    if (bitmap != null) {
                        bitmap.recycle();
                    }
                    subscriber.onNext(bytes);
                }
            }
        }).subscribeOn(Schedulers.io())//指定数据发射(上方的subscribe方法)在哪个线程执行
                .observeOn(AndroidSchedulers.mainThread())//observeOn方法决定他下面的方法执行在哪个线程中
                .subscribe(new Observer<byte[]>() {
                    @Override
                    public void onError(Throwable e) {
                        setToast(e.getMessage());
                    }
                    @Override
                    public void onComplete() {
                        Glide.with(context).load(context.getExternalFilesDir(null) + Image_url).into(imageView);
                    }
                    @Override
                    public void onSubscribe(Disposable d) {
                    }
                    @Override
                    public void onNext(byte[] res) {
                        Glide.with(context).load(res).into(imageView);
                    }
                });
    }

    public void setToast(String message){
        Toast.makeText(context,message, Toast.LENGTH_SHORT).show();
    }

    //初始化一个OssService用来上传下载
    public OSS initOSS(String endpoint) {
        //        如果希望直接使用accessKey来访问的时候，可以直接使用OSSPlainTextAKSKCredentialProvider来鉴权。
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKeyId, accessKeySecret);
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        OSS oss = new OSSClient(context, endpoint, credentialProvider, conf);
        Log.d("oss", "initOSS");
        return oss;
    }

    //根据ImageView大小自动缩放图片
    public Bitmap autoResizeFromStream(InputStream stream) throws IOException {

        byte[] data;
        {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = stream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            outStream.close();
            data = outStream.toByteArray();
        }

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(data, 0, data.length, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, imageView.getWidth(), imageView.getHeight());
//            Log.d("ImageHeight", String.valueOf(options.outHeight));
//            Log.d("ImageWidth", String.valueOf(options.outWidth));
//            Log.d("Height", String.valueOf(imageView.getWidth()));
//            Log.d("Width", String.valueOf(imageView.getWidth()));
        //options.inSampleSize = 10;

//            Log.d("SampleSize", String.valueOf(options.inSampleSize));
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeByteArray(data, 0, data.length, options);
    }

    //计算图片缩放比例
    public int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }

}
}